class AddressManager {
  constructor() {
    this.addresses = {}; // 本地缓存的地址对象
    this.selectedAddressId = null; // 当前选中的地址 ID
    this.loadFromStorage();
    this.clearSelectedAddressId(); // 清空选中地址 ID
  }

  // 从本地存储加载地址数据
  loadFromStorage() {
    try {
      const storedAddresses = wx.getStorageSync('addresses');
      const selectedAddressId = wx.getStorageSync('selectedAddressId');
      if (storedAddresses) {
        this.addresses = storedAddresses;
      }
      if (selectedAddressId) {
        this.selectedAddressId = selectedAddressId;
      }
    } catch (e) {
      console.error('Failed to load address data from storage:', e);
    }
  }

  // 清空选中地址 ID
  clearSelectedAddressId() {
    this.selectedAddressId = null;
    this.saveToStorage();
  }
  
  // 保存地址数据到本地存储
  saveToStorage() {
    try {
      wx.setStorageSync('addresses', this.addresses);
      wx.setStorageSync('selectedAddressId', this.selectedAddressId);
    } catch (e) {
      console.error('Failed to save address data to storage:', e);
    }
  }

  // 获取所有缓存的地址
  getAllAddresses() {
    return this.addresses;
  }

  // 获取当前选中的地址 ID
  getSelectedAddressId() {
    return this.selectedAddressId;
  }

  // 设置当前选中的地址 ID
  setSelectedAddressId(addressId) {
    this.selectedAddressId = addressId;
    this.saveToStorage();
  }

  // 添加或更新地址
  updateAddress(addressId, addressData) {
    this.addresses[addressId] = {
      ...this.addresses[addressId], // 保留已有字段
      ...addressData, // 更新字段
    };
    this.saveToStorage();
  }

  // 删除地址
  deleteAddress(addressId) {
    if (this.addresses[addressId]) {
      delete this.addresses[addressId];
      this.saveToStorage();
    }
  }

  // 将所有地址设置为非默认
  setAllAddressesNonDefault() {
    Object.keys(this.addresses).forEach((addressId) => {
      this.addresses[addressId].isDefault = false;
    });
    this.saveToStorage();
  }
}

module.exports = new AddressManager();